import cv2 as cv
import os
import time
import numpy as np

DIR = './resources/'
KEY_SAVE = 's'
KEY_QUIT = 'q'
KEY_MODE_ADD = 'w'
KEY_MODE_MIN = 'e'
KEY_PAGE_ADD = 'r'
KEY_PAGE_MIN = 'd'
KEY_RECT_CHANGE = 'j'
points = []
rect_style = False


def OnMouse(event, x, y, flags, param):
	if event == cv.EVENT_LBUTTONDOWN:
		points.append((x, y))
		print(points)
		cv.circle(img, (x, y), 5, color=(0, 255, 255), thickness=3)
		if len(points) == 4:
			for i in range(len(points)):
				cv.line(img, points[i], points[(i + 1) % len(points)], (0, 255, 0), 3)
	elif event == cv.EVENT_MOUSEMOVE and flags == (cv.EVENT_FLAG_CTRLKEY | cv.EVENT_FLAG_LBUTTON):
		print('writing')
		cv.rectangle(copy, points[0], (x, y), color=(1, 1, 1, 1))
		# cv.drawContours(img, contours=points, contourIdx=-1, color=(255, 100, 100), thickness=1)


def WritePhoto():
	name = "./data/" + str(mode) + '/' + time.strftime("%H%M%S", time.localtime()) + ".jpg"
	horizon = []
	vertices = []
	for point in points:
		horizon.append(point[0])
		vertices.append(point[1])
	left, right = min(horizon), max(horizon)
	top, bottom = min(vertices), max(vertices)

	if rect_style:
		print(points)
		rect = cv.minAreaRect(points=points)
		box = cv.boxPoints(rect)
		box = np.int0(box)
		center, size, angle = rect[0], rect[1], rect[2]
		center, size = tuple(map(int, center)), tuple(map(int, size))

		# get row and col num in img
		height, width = img.shape[0], img.shape[1]

		# calculate the rotation matrix
		M = cv.getRotationMatrix2D(center, angle, 1)
		# rotate the original image
		img_rot = cv.warpAffine(img, M, (width, height))

		# now rotated rectangle becomes vertical and we crop it
		img_crop = cv.getRectSubPix(img_rot, size, center)
		cv.imshow("now", img_crop)
		cv.waitKey(0)
		print(box)
	else:
		roi = copy[top:bottom, left:right, :3]
		cv.imshow("roi", roi)
		points.clear()
		cv.destroyWindow("roi")

	cv.imwrite(name, roi)
	print(name)


k = 0
ptr = 1
mode = 4
photos = []

cv.namedWindow('image')
cv.namedWindow('num')

cv.setMouseCallback('image', OnMouse)
files = os.listdir(DIR)

for file in files:
	if file.endswith('.jpg') or file.endswith('.png'):
		photos.append(DIR + file)
print(photos)
# cell = []
# for photo in photo:
# 	img = cv.imread(photo)
# 	cell.append(cv.resize(img,(43, 32)))


black = np.ones((300, 500, 3), dtype=np.uint8)
label1 = "Type in 'S' : Save the image"
label2 = "Type in 'Q' : Quit"
label3 = "Type in 'e' : Num -"
label4 = "Type in 'w' : Num +"
label5 = "Type in 'd' : Pre file"
label6 = "Type in 'r' : Next file"
label7 = "Type in 'J' : Change rectangle style"
cv.putText(black, label1, (0, 20), cv.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0))
cv.putText(black, label2, (0, 45), cv.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0))
cv.putText(black, label3, (0, 70), cv.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0))
cv.putText(black, label4, (0, 95), cv.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0))
cv.putText(black, label5, (0, 120), cv.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0))
cv.putText(black, label6, (0, 145), cv.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0))
cv.putText(black, label7, (0, 170), cv.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0))
# cv.putText(black, "File name : " + photos[0], (0, 200), cv.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0))

img = cv.imread(photos[0])
copy = img.copy()
cv.imshow("num", black)
cv.setWindowTitle('image', photos[0])
cv.setWindowTitle("num", str(mode))

while True:
	now_file = photos[ptr]
	if k == ord(KEY_PAGE_ADD) or k == ord(KEY_PAGE_MIN):
		if k == ord(KEY_PAGE_ADD):
			ptr += 1
			if ptr > len(photos) - 1:
				ptr = 0
		elif k == ord(KEY_PAGE_MIN):
			ptr -= 1
			if ptr < 0:
				ptr = len(photos) - 1

		points.clear()
		now_file = photos[ptr]
		cv.setWindowTitle('image', now_file)
		cv.putText(black, "File name : {0}".format(now_file), (0, 200), cv.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0))
		img = cv.imread(now_file)
		copy = img.copy()

	if k == ord(KEY_SAVE):
		if len(points) == 4:
			WritePhoto()

	elif k == ord(KEY_MODE_ADD) or k == ord(KEY_MODE_MIN):
		if k == ord(KEY_MODE_MIN):
			mode -= 1
			if mode < 1:
				mode = 8
		elif k == ord(KEY_MODE_ADD):
			mode += 1
			if mode > 8:
				mode = 1
		cv.setWindowTitle("num", str(mode))
		cv.putText(black, "Num : {0}".format(str(mode)), (0, 225), cv.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0))

	elif k == ord(KEY_RECT_CHANGE):
		rect_style = not rect_style
		if rect_style:
			print("minArea")
		else:
			print("Bounding")
	elif k == ord(KEY_QUIT):
		break

	cv.imshow('image', img)
	k = cv.waitKey(1)

cv.destroyAllWindows()
